import store from "@/store"
/**
 * 验证手机号码
 */
export function checkPhone(phone) {
	if (!(/^1[3456789]\d{9}$/.test(phone))) {
		return false;
	}
	return true
}

/**
 * 验证两个object 是否相同
 * @param {Object} obj  [需要进行验证的数据1]
 * @param {Object} newObj [需要进行验证的数据2]
 */
export function objSame(obj, newObj) {
	let bol = true;
	if (obj && newObj &&  Object.keys(obj).length != Object.keys(newObj).length) {
		return false;
	}
	for (let key in obj) {
		if (obj[key] instanceof Object) {
			bol = objSame(obj[key], newObj[key]);
			if (!bol) {
				break;
			}
		} else if (obj[key] instanceof Array) {
			bol = arrSame(obj[key], newObj[key])
			if (!bol) {
				break;
			}
		} else if (obj[key] != newObj[key]) {
			bol = false;
			break;
		}
	}
	return bol
}

/**
 * 验证两个数组是否相同
 * @param {Array} arr  [需要进行验证的数据1]
 * @param {Array} newArr [需要进行验证的数据2]
 * @param {Boolean} isSort [是否需要按顺序验证]
 * @param {Number} type [默认值0， 1：数据2包含数据1,0：数据2完全等于数据1]
 */
export function arrSame(arr, newArr, isSort,type=0) {
	console.log(arr, newArr, isSort,type)
	let bol = true
	
	if (!isSort) {
		arr = arr.sort()
		newArr = newArr.sort()
	}
	if(type==0){
		if (arr.length != newArr.length) {
			return false
		}
		for (let i = 0, n = arr.length; i < n; i++) {
			if (arr[i] instanceof Array) {
				bol = arrSame(arr[i], newArr[i])
				if (!bol) {
					break;
				}
			} else if (arr[i] instanceof Object) {
				bol = objSame(arr[i], newArr[i])
				if (!bol) {
					break;
				}
			} else if (arr[i] != newArr[i]) {
				bol = false;
				break;
			}
		}
	}else{
		if(arr && newArr && newArr.length<arr.length){
			return false;
		}
		let arrLength=arr.length
		let thisNum=0
		arr.forEach(item=>{
			if(newArr.indexOf(item)!=-1){
				thisNum++
			}
		})
		if(arrLength!=thisNum){
			bol = false;
		}
	}
	
	return bol;
}

	
/**
 * 返回上一页执行方法
 */
export function hdNavigateBack(index=1) {
	return new Promise((r, j) => {
		const pages = getCurrentPages();
		const beforePage = pages[pages.length - (index+1)];
		if (!beforePage) {
			// uni.showToast({
			// 	title: '前面没有页面啦~',
			// 	icon: 'none'
			// })
			j()
		}
		// #ifdef H5
		r({
			beforePage,
			navigateBack() {
				uni.navigateBack({
					delta:index
				})
			}
		})
		// #endif
		// #ifndef H5
		r({
			beforePage: beforePage.$vm,
			navigateBack() {
				uni.navigateBack({
					delta:index
				})
			}
		})
		// #endif
	})

}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */
export function parseTime(time, cFormat) {
	if (arguments.length === 0 || !time) {
		return null;
	}
	const format = cFormat || "{y}-{m}-{d} {h}:{i}:{s}";
	let date;
	if (typeof time === "object") {
		date = time;
	} else {
		if (typeof time === "string") {
			if (/^[0-9]+$/.test(time)) {
				// support "1548221490638"
				time = parseInt(time);
			} else {
				// support safari
				// https://stackoverflow.com/questions/4310953/invalid-date-in-safari
				time = time.replace(new RegExp(/-/gm), "/");
			}
		}

		if (typeof time === "number" && time.toString().length === 10) {
			time = time * 1000;
		}
		date = new Date(time);
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay(),
	};
	const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
		const value = formatObj[key];
		// Note: getDay() returns 0 on Sunday
		if (key === "a") {
			return ["日", "一", "二", "三", "四", "五", "六"][value];
		}
		return value.toString().padStart(2, "0");
	});
	return time_str;
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
	if (("" + time).length === 10) {
		time = parseInt(time) * 1000;
	} else {
		time = +time;
	}
	const d = new Date(time);
	const now = Date.now();

	const diff = (now - d) / 1000;

	if (diff < 30) {
		return "刚刚";
	} else if (diff < 3600) {
		// less 1 hour
		return Math.ceil(diff / 60) + "分钟前";
	} else if (diff < 3600 * 24) {
		return Math.ceil(diff / 3600) + "小时前";
	} else if (diff < 3600 * 24 * 2) {
		return "1天前";
	}
	if (option) {
		return parseTime(time, option);
	} else {
		return (
			d.getMonth() +
			1 +
			"月" +
			d.getDate() +
			"日" +
			d.getHours() +
			"时" +
			d.getMinutes() +
			"分"
		);
	}
}
/* 倒计时格式化
 time: 倒计时秒数 (秒)
 space: 中间间隔，默认为冒号
 */
export function totaltime(time, space = ':',type='String') {
	let totaltime_array=time.toString().split('_')
	let totaltime = Number(totaltime_array[0])
	let that = this
	var h, m, s, d

	function test(num) {
		if (num < 10) {
			num = "0" + num
		}
		return num
	}

	let returnString=''
	if (totaltime > 0) {
		d = Math.floor(totaltime / 60 / 60 / 24) * 24
		h = Math.floor(totaltime / 60 / 60 % 24)
		m = Math.floor(totaltime / 60 % 60)
		s = Math.floor(totaltime % 60)
		//获取时分秒
		h = d + h
		h = test(h)
		m = test(m)
		s = test(s)
		let timeArray=[]
		if(d>0)timeArray.push(d)
		if(h>0 || totaltime_array.length<=1)timeArray.push(h)
		timeArray.push(m)
		timeArray.push(s)
		returnString=timeArray.join(space)
		// if (h <= 0) {
		// 	returnString= `${m}${space}${s}`
		// }
		// returnString= `${h}${space}${m}${space}${s}` // 每个时间的显示格式
	} else {
		returnString= `00${space}00`
	}
	if(type=='String'){
		return returnString
	}else{
		return returnString.split(space)
	}
}

/**
    @param array整型数组，且已经按照从小到大排好了序的
    @param val 传入的值
    @return 返回对应范围的下标
    ** 说明：
    根据指定的值，在array查找第一个比它大的值，返回对应的索引，通过索引在voltageDataType获取对应的类型
    1：如果值小于array最小的值时，则获取最低类型。所以voltageDataType前被赋予了个0
    2：如果值大于array最大的值时，则类型最高一档

    ** vue 请使用vue调用方法
*/
export function searchIndexType(array, val) {
	// 如果值小于array最小的值时，则获取最低档类型
	if (val < Math.min.apply(null, array)) {
		return 0
	}

	// 如果值大于array最大的值时，则类型最高一档
	if (val > Math.max.apply(null, array)) {
		return array.length - 1
	}

	var idx = 0;
	var i = 0;
	var j = array.length
	for (i; i < j; i++) {
		if (array[i] > val) {
			idx = i
			break
		}
	}
	return idx
}
/**
 * 防抖函数
 * @param method 事件触发的操作
 * @param delay 触发之后多长时间后执行
 * @returns {Function}
 */
export function debounce(method, delay) {
	let timer = null;
	return function() {
		let self = this,
			args = arguments;
		clearTimeout(timer);
		timer = setTimeout(function() {
			method.apply(self, args);
		}, delay);
	}
}
/**
 * 节流函数
 * @param method 事件触发的操作
 * @param mustRunDelay 间隔多少毫秒需要触发一次事件
 */
export function throttle(method, mustRunDelay) {
	let timer,
		args = arguments,
		start;
	return function loop() {
		let self = this;
		let now = Date.now();
		if (!start) {
			start = now;
		}
		if (timer) {
			clearTimeout(timer);
		}
		if (now - start >= mustRunDelay) {
			method.apply(self, args);
			start = now;
		} else {
			timer = setTimeout(function() {
				loop.apply(self, args);
			}, 50);
		}
	}
}
/**
 * 判断字符串是否为json字符串
 * @param {String} str
 */
export function isJSON(str) {
	if (typeof str == "string") {
		try {
			let obj = JSON.parse(str);
			return !!(typeof obj == "object" && obj);
		} catch (e) {
			return false;
		}
	}
	return false
}

/**
 * 对象深拷贝
 */
export function deepClone(obj) {
	let objClone = Array.isArray(obj) ? [] : {}
	if (obj && typeof obj === 'object') {
		for (let key in obj) {
			if (obj[key] && typeof obj[key] === 'object') {
				objClone[key] = deepClone(obj[key])
			} else {
				objClone[key] = obj[key]
			}
		}
	}
	return objClone
}

/**
 * 删除对象里的某个或几个属性
 */
export function deleteObjValue(obj, params) {
	if (typeof obj != 'object') obj = {}
	if (typeof params === 'string') {
		obj[params] = undefined
	} else if (typeof params === 'object') {
		for (const key in params) {
			if (Object.hasOwnProperty.call(params, key)) {
				obj[key] = undefined
			}
		}
	}
	return obj
}

//字符串转base64
export function encodeBase64(str) {
	// 对字符串进行编码
	let encode = encodeURI(str);
	// 对编码的字符串转化base64
	let base64 = btoa(encode);
	return base64;
}

// base64转字符串
export function decodeBase64(base64) {
	// 对base64转编码
	let decode = atob(base64);
	// 编码转字符串
	let str = decodeURI(decode);
	return str;
}

// 判断左滑还是右滑
export function touchDirection() {
	let lastX = 0,
		lastY = 0,
		direction = 'none'
	return (currentX, currentY) => {
		let tx = currentX - lastX,
			ty = currentY - lastY
		if (Math.abs(tx) > Math.abs(ty)) {
			//左右方向滑动
			if (tx < 0)
				direction = "left"
			else if (tx > 0)
				direction = "right"
		} else {
			//上下方向滑动
			if (ty < 0)
				direction = "top"
			else if (ty > 0)
				direction = "bottom"
		}
		lastX = currentX
		lastY = currentY
		return direction
	}
}

// 保存图片到本地
export function saveImage(img, callback) {
	if (!img) return new Error('图片地址不能为空')
	uni.getSetting({
		success(res) {
			// console.log(res.authSetting)
			const auths = res.authSetting
			// 如果有读写相册权限，则保存图片，如果没有提示用户授权
			if (auths['scope.writePhotosAlbum']) {
				save(img).then(res => {
					callback && callback({
						code: 1,
						msg: '保存成功'
					})
				}).catch(err => {
					callback && callback({
						code: 2,
						msg: '保存失败'
					})
				})
			} else {
				uni.showModal({
					title: '提示',
					content: '您已关闭小程序保存图片的权限！去开启权限？',
					success(res) {
						if (res.confirm) {
							uni.authorize({
								scope: 'scope.writePhotosAlbum',
								success: () => {
									save(img).then(res => {
										callback && callback({
											code: 1,
											msg: '保存成功'
										})
									}).catch(err => {
										callback && callback({
											code: 2,
											msg: '保存失败'
										})
									})
								},
								fail: () => {
									openWritePhotosSetting().then(res => {
										save(img).then(res => {
											callback && callback({
												code: 1,
												msg: '保存成功'
											})
										}).catch(err => {
											callback && callback({
												code: 2,
												msg: '保存失败'
											})
										})
									}).catch(err => {
										uni.showToast({
											title: '您已关闭相册读写权限，需手动点击右上角设置->打开相册使用权限',
											icon: 'none'
										})
										callback && callback({
											code: 0
										})
									})
								}
							})

						} else if (res.cancel) {
							callback && callback({
								code: 0,
								msg: '无权限'
							})
							console.log('取消授权');
						}
					}
				})
			}
		},
		fail(err) {
			callback && callback({
				code: 0,
				msg: '获取授权失败'
			})
		}
	})
}

function openWritePhotosSetting() {
	return new Promise((r, j) => {
		uni.openSetting({
			success: (authRes) => {
				const auths = authRes.authSetting
				if (auths['scope.writePhotosAlbum']) {
					r()
				} else {
					j()
				}
			},
			fail: (err) => {
				j(err)
			}
		})
	})
}

function save(img) {
	return new Promise((r, j) => {
		uni.saveImageToPhotosAlbum({
			filePath: img,
			success: () => {
				uni.showToast({
					title: "保存成功"
				})
				r()
			},
			fail: (err) => {
				uni.showToast({
					title: "保存失败",
					icon: "none"
				})
				j()
			}
		})
	})
}

function typeOf(value){
        let str=Object.prototype.toString.call(value)
        str=str.replace('object','').replace('[','').replace(']','')
        str=str.replace(/(^\s*)|(\s*$)/g, "").toLowerCase()
        if(value=='null' || value=='undefined'){
            str=typeof(value) 
        }
        return str
 }
 






 
 // 继续订阅
 function nextTemplateInform(itemSettings,template_id,cb){
	 let templateArray=[]
	 let thisIdarray=[]
	 if(typeOf(template_id)=='array'){
		 thisIdarray=template_id
	 }else{
		 thisIdarray=template_id.split(',')
	 }
	 thisIdarray.forEach((item=>{
		 if (itemSettings) {
		 		if (itemSettings[template_id] == "reject") {
		 			templateArray.push(item)
		 		}else{
		 			templateArray.push(item)
		 		}
		 	} else {
		 		templateArray.push(item)
		 	}
	 }))
	 if(cb)cb(templateArray)
	 
	 
 }

export function templateInform(content = '消息订阅!', template_id,cb=null) {
	if (!template_id || template_id=='') {
		template_id = store.state.app.weixin_msg_template_id.voucher_notify
	}
	uni.getSetting({
		withSubscriptions: true,
		success: (res) => {
			var itemSettings = res.subscriptionsSetting.itemSettings;
			nextTemplateInform(itemSettings,template_id,templateArray=>{
				console.log(templateArray,'---templateArray---')
				if(templateArray){
					if(content==''){
						templateMessage(templateArray,cb)
						return false;
					}
					uni.showModal({
						title: '温馨提示',
						content: content,
						showCancel: false,
						confirmText: '查看',
						success: res => {
							if (res.confirm) {
								templateMessage(templateArray,cb)
							}
						}
						 
					})
				}
			})
			
		},
		// complete:(res)=>{
		// 	uni.showModal({
		// 		content:JSON.stringify(res)
		// 	})
		// }
	})
}

export function getSceneData(scene) {
	let _scene = decodeURIComponent(scene)
	if (_scene !== 'undefined') {
		let params = {}
		let urls = _scene.split('&')
		urls.forEach((ele, idx) => {
			let a = urls[idx].split('=')
			params[a[0]] = a[1]
		})
		return params
	} else {
		return false
	}
}

export function getCurrentPageUrl() {
	const pages = getCurrentPages();
	const currentPage = pages[pages.length - 1];
	const url = currentPage.route;
	const options = currentPage.options;
	let urlWithArgs = `/${url}?`;
	for (let key in options) {
		const value = options[key];
		urlWithArgs += `${key}=${value}&`;
	}
	urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1);
	return {
		fullPath: urlWithArgs,
		route: url,
		options: options
	};
};


export function getCapsuleOrBarHeight(type = 1) {
	// 胶囊 + 顶部 => 1
	// 顶部 => 2
	const statuBar = uni.getSystemInfoSync().statusBarHeight;
	// 获取胶囊数据
	const custom = uni.getMenuButtonBoundingClientRect()
	// 获取导航栏（标题栏高度）高度
	const navigationBarHeight = custom.height + (custom.top - statuBar) * 2
	// 总体高度 = 状态栏高度+导航栏高度
	const navAllHeight = navigationBarHeight + statuBar
	return type == 1 ? navAllHeight : statuBar
}


export const setOperationSwiper = (fromname, toname) => {  
  const pageOperationKey = {
	  index: 'indexBannerPage',
	  prize: 'storyHousePage',
	  mysteryBoxStatus: 'orderListPage',
	  orderDetails: 'orderDetailPage',
    logisticsInformation:'logisticsDetailPage'
  }
	// if (fromname == 'index') {
	// 	store.commit('steryBox/app/CHANGE_OPERATION_AND_PAGE_RECORD', { key: pageOperationKey['index'], status: false })
	// 	store.commit('steryBox/app/CHANGE_OPERATION_AND_PAGE_RECORD', { key: pageOperationKey['prize'], status: false })
	// } else {
	// 	store.commit('steryBox/app/CHANGE_OPERATION_AND_PAGE_RECORD', { key: pageOperationKey[fromname], status: false })
	// }

	// if (toname == 'index') {
	// 	store.commit('steryBox/app/CHANGE_OPERATION_AND_PAGE_RECORD', { key: pageOperationKey['index'], status: true })
	// 	store.commit('steryBox/app/CHANGE_OPERATION_AND_PAGE_RECORD', { key: pageOperationKey['prize'], status: true })
	// }else {
	// 	store.commit('steryBox/app/CHANGE_OPERATION_AND_PAGE_RECORD', { key: pageOperationKey[toname], status: true })
	// }
}